package reflect;

import reflect.annotation.AutoRunClass;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;

@AutoRunClass
public class Test2_2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, URISyntaxException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /**
         * 实例化与当前类Test2在同一个包中的所有类
         * 用无参构造器实例化
         */
//        找到Test2.class所在的文件路径 F:\jsd2302_1\jsd2302\src\reflect
        File dir=new File(Test2.class.getResource(".").toURI());
//        得到Test2所在的包名
        String packageName = Test2.class.getPackage().getName();
//        得到类路径下的所有子文件F:\jsd2302_1\jsd2302\src\reflect\Person.class
        File[] subs = dir.listFiles(file -> file.getName().endsWith(".class"));
//        遍历所有子文件
        for (File sub:subs){
            String fileName = sub.getName();
            String name = fileName.substring(0, fileName.indexOf("."));
            String className=packageName+"."+name;
            Class cls = Class.forName(className);
            Constructor constructor = cls.getConstructor();
            Object o = constructor.newInstance();
            System.out.println(o);
        }


    }
}
